#include <QCoreApplication>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class OneHandRoadPainting
{
public:
    long long fastest(vector <int> dStart, vector <int> dEnd, int paintPerBrush);
};
long long OneHandRoadPainting::fastest(vector<int> dStart, vector<int> dEnd, int paintPerBrush)
{
    long long disSum;
    long long result;
    vector<long long> res;
    int remainerPaint;
    if (paintPerBrush<=0) return 0;
    disSum=dStart[0];
    remainerPaint=paintPerBrush;
    for (int i=0;i<dEnd.size();i++)
    {
        int shang=(dEnd[i]-dStart[i])/paintPerBrush;
        int yushu=(dEnd[i]-dStart[i])%paintPerBrush;
        if (remainerPaint>=(dEnd[i]-dStart[i])%paintPerBrush && remainerPaint<dEnd[i]-dStart[i])
        {
            disSum+=remainerPaint+2*(dStart[i]+remainerPaint);
            dStart[i]=dStart[i]+remainerPaint;
            i--;
            remainerPaint=paintPerBrush;
        }
        else if(remainerPaint<(dEnd[i]-dStart[i])%paintPerBrush )
        {
            disSum+=2*dStart[i];
            i--;
            remainerPaint=paintPerBrush;
        }
        else if(remainerPaint>=dEnd[i]-dStart[i])
        {
            disSum+=dEnd[i]-dStart[i];
            remainerPaint=remainerPaint-(dEnd[i]-dStart[i]);
            if(i+1<dEnd.size())
            {
                if((remainerPaint>=(dEnd[i+1]-dStart[i+1])%paintPerBrush
                        && (dEnd[i+1]-dStart[i+1])%paintPerBrush!=0)||remainerPaint>=dEnd[i+1]-dStart[i+1])
                    disSum+=dStart[i+1]-dEnd[i];
                else
                {
                    disSum+=dEnd[i]+dStart[i+1];
                    remainerPaint=paintPerBrush;
                }

            }
        }
    }
    disSum+=*(--dEnd.end());
    return disSum;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int paintPer = 2;
    vector<int> dStart{1,10,20};
    vector<int> dEnd{4,13,22};
    OneHandRoadPainting test;
    cout<<test.fastest(dStart,dEnd,paintPer);

    return a.exec();
}
